package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.wms.entity.WmsInventory;
import org.jeecg.modules.wms.entity.WmsInventoryHistory;
import org.jeecg.modules.wms.entity.WmsWarehouseLocation;
import org.jeecg.modules.wms.mapper.WmsInventoryHistoryMapper;
import org.jeecg.modules.wms.mapper.WmsWarehouseLocationMapper;
import org.jeecg.modules.wms.service.IWmsInventoryHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Calendar;

/**
 * 库存历史记录服务实现
 */
@Slf4j
@Service
public class WmsInventoryHistoryServiceImpl extends ServiceImpl<WmsInventoryHistoryMapper, WmsInventoryHistory> implements IWmsInventoryHistoryService {
    @Autowired
    private WmsWarehouseLocationMapper warehouseLocationMapper;
    
    @Override
    public IPage<WmsInventoryHistory> queryHistoryPageList(Page<WmsInventoryHistory> page,Map<String, Object> history) {
        return baseMapper.queryHistoryPageList(page, history);
    }
    
    @Override
    public List<WmsInventoryHistory> queryHistoryList(Map<String, Object> query) {
        return baseMapper.queryHistoryList(query);
    }
    
    @Override
    public boolean recordHistory(WmsInventory inventory, BigDecimal beforeQuantity, BigDecimal changeQuantity, 
                              BigDecimal afterQuantity, Integer businessType, String businessNo, 
                              String operator, String remark) {
        if (inventory == null) {
            log.error("记录库存历史失败：库存信息为空");
            return false;
        }
        
        try {
            WmsInventoryHistory history = new WmsInventoryHistory();
            history.setId(UUIDGenerator.generate());
            history.setInventoryId(inventory.getId());
            history.setMaterialCode(inventory.getMaterialCode());
            history.setMaterialName(inventory.getMaterialName());
            history.setMaterialType(inventory.getMaterialType());
            history.setSpecification(inventory.getSpecification());
            history.setColor(inventory.getColor());
            history.setUnit(inventory.getUnit());
            history.setWarehouseId(inventory.getWarehouseId());
            history.setWarehouseName(inventory.getWarehouseName());
            history.setLocationId(inventory.getLocationId());
            history.setMaterialSeries(inventory.getMaterialSeries());
            //根据locationID查询库位名称
            WmsWarehouseLocation wmsWarehouseLocation = warehouseLocationMapper.selectById(inventory.getLocationId());
            if(wmsWarehouseLocation != null){
                history.setLocationName(wmsWarehouseLocation.getLocationName());
            }
            history.setBusinessType(businessType);
            history.setBusinessNo(businessNo);
            history.setBeforeQuantity(beforeQuantity);
            history.setChangeQuantity(changeQuantity);
            history.setAfterQuantity(afterQuantity);
            history.setBatchNo(inventory.getBatchNo());
            history.setMaterialImages(inventory.getMaterialImages());
            history.setSupplier(inventory.getSupplier());
            history.setOperator(operator);
            history.setOperateTime(new Date());
            history.setRemark(remark);
            history.setCreateBy(operator);
            history.setCreateTime(new Date());
            history.setUpdateBy(operator);
            history.setUpdateTime(new Date());
            history.setTenantId(inventory.getTenantId());
            
            return save(history);
        } catch (Exception e) {
            log.error("记录库存历史失败", e);
            return false;
        }
    }
    
    @Override
    public boolean recordHistoryWithCost(WmsInventory inventory, BigDecimal beforeQuantity, BigDecimal changeQuantity, 
                              BigDecimal afterQuantity, BigDecimal beforeTotalCost, BigDecimal changeTotalCost, 
                              BigDecimal afterTotalCost, Integer businessType, String businessNo, 
                              String operator, String remark) {
        if (inventory == null) {
            log.error("记录库存历史失败：库存信息为空");
            return false;
        }
        
        try {
            WmsInventoryHistory history = new WmsInventoryHistory();
            history.setId(UUIDGenerator.generate());
            history.setInventoryId(inventory.getId());
            history.setMaterialCode(inventory.getMaterialCode());
            history.setMaterialName(inventory.getMaterialName());
            history.setMaterialType(inventory.getMaterialType());
            history.setSpecification(inventory.getSpecification());
            history.setColor(inventory.getColor());
            history.setUnit(inventory.getUnit());
            history.setWarehouseId(inventory.getWarehouseId());
            history.setWarehouseName(inventory.getWarehouseName());
            history.setLocationId(inventory.getLocationId());
            //根据locationID查询库位名称
            WmsWarehouseLocation wmsWarehouseLocation = warehouseLocationMapper.selectById(inventory.getLocationId());
            if(wmsWarehouseLocation != null){
                history.setLocationName(wmsWarehouseLocation.getLocationName());
            }
            history.setBusinessType(businessType);
            history.setBusinessNo(businessNo);
            history.setBeforeQuantity(beforeQuantity);
            history.setChangeQuantity(changeQuantity);
            history.setAfterQuantity(afterQuantity);
            history.setUnitCost(inventory.getUnitCost());
            history.setBeforeTotalCost(beforeTotalCost);
            history.setChangeTotalCost(changeTotalCost);
            history.setAfterTotalCost(afterTotalCost);
            history.setBatchNo(inventory.getBatchNo());
            history.setMaterialImages(inventory.getMaterialImages());
            history.setSupplier(inventory.getSupplier());
            history.setOperator(operator);
            history.setOperateTime(new Date());
            history.setRemark(remark);
            history.setCreateBy(operator);
            history.setCreateTime(new Date());
            history.setUpdateBy(operator);
            history.setUpdateTime(new Date());
            history.setTenantId(inventory.getTenantId());
            
            return save(history);
        } catch (Exception e) {
            log.error("记录库存历史失败", e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getStatisticsData(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取时间范围
            String timeRange = (String) params.getOrDefault("timeRange", "month");
            Date startDate = null;
            Date endDate = new Date(); // 当前时间作为结束时间
            
            // 根据时间范围计算开始时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endDate);
            
            switch (timeRange) {
                case "day":
                    // 当天
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MILLISECOND, 0);
                    startDate = calendar.getTime();
                    break;
                case "week":
                    // 近一周
                    calendar.add(Calendar.DAY_OF_MONTH, -7);
                    startDate = calendar.getTime();
                    break;
                case "month":
                    // 近一月
                    calendar.add(Calendar.MONTH, -1);
                    startDate = calendar.getTime();
                    break;
                case "year":
                    // 近一年
                    calendar.add(Calendar.YEAR, -1);
                    startDate = calendar.getTime();
                    break;
                default:
                    // 默认近一月
                    calendar.add(Calendar.MONTH, -1);
                    startDate = calendar.getTime();
            }
            
            // 添加时间范围参数
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            
            // 1. 获取业务类型分布统计
            List<Map<String, Object>> businessTypeStats = baseMapper.getBusinessTypeStatistics(params);
            result.put("businessTypeStats", businessTypeStats);
            
            // 2. 获取物料类型分布统计
            List<Map<String, Object>> materialTypeStats = baseMapper.getMaterialTypeStatistics(params);
            result.put("materialTypeStats", materialTypeStats);
            
            // 3. 获取时间趋势统计
            List<Map<String, Object>> timeStats = baseMapper.getTimeStatistics(params);
            result.put("timeStats", timeStats);
            
            return result;
        } catch (Exception e) {
            log.error("获取库存历史统计数据失败", e);
            return result;
        }
    }
} 